package com.ruoyi.web.controller.module.estate;

import java.util.List;
import java.util.Arrays;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.QRCodeUtilEx;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.domain.module.estate.Estate;
import com.ruoyi.system.domain.module.estate.EstateBuildFloor;
import com.ruoyi.system.domain.module.estate.EstateRoom;
import com.ruoyi.system.domain.module.event.EventTerminals;
import com.ruoyi.system.service.module.estate.IEstateBuildFloorService;
import com.ruoyi.system.service.module.estate.IEstateRoomService;
import com.ruoyi.system.service.module.estate.IEstateService;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.web.controller.common.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 楼栋的 楼层数据Controller
 *
 * @author ruoyi
 * @date 2023-12-31
 */
@Validated
@Api(value = "楼栋的 楼层数据控制器", tags = {"楼栋的 楼层数据管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/estate/build/floor")
public class EstateBuildFloorController extends BaseController {

    private final IEstateBuildFloorService estateBuildFloorService;
	private final IEstateService estateService;
	private final IEstateRoomService estateRoomService;

	@Value("${ruoyi.profile}")
	private String uploadPath;

	@Value("${ruoyi.imgUrl}")
	private String imgUrl;

    /**
     * 查询楼栋的 楼层数据列表
     */
    @ApiOperation("查询楼栋的 楼层数据列表")
    @PreAuthorize("@ss.hasPermi('module:estateFloor:list')")
    @GetMapping("/list")
    public List<EstateBuildFloor> list(@Validated EstateBuildFloor estateBuildFloor) {
        QueryWrapper<EstateBuildFloor> qw = new QueryWrapper<>();
		if (estateBuildFloor.getEstateId()!=null){
			qw.eq("estate_id",estateBuildFloor.getEstateId());
		}
		if(estateBuildFloor.getBuildId()!= null){
			qw.eq("build_id", estateBuildFloor.getBuildId());
		}
		if(estateBuildFloor.getUnitId()!= null){
			qw.eq("unit_id", estateBuildFloor.getUnitId());
		}
		qw.orderByAsc("sort");;
        List<EstateBuildFloor> list = estateBuildFloorService.list(qw);
		if(CollUtil.isNotEmpty(list)){
			for (EstateBuildFloor floor : list){
				if(StrUtil.isNotEmpty(floor.getQrCode())){
					floor.setQrCode(imgUrl + floor.getQrCode());
				}

				QueryWrapper<EstateRoom> qwRoom = new QueryWrapper<>();
				qwRoom.eq("floor_id", floor.getId());
				long roomCount = estateRoomService.count(qwRoom);
				floor.setRoomCount(roomCount);
			}
		}
        return list;
    }

    /**
     * 导出楼栋的 楼层数据列表
     */
    @ApiOperation("导出楼栋的 楼层数据列表")
    @PreAuthorize("@ss.hasPermi('module:estateFloor:export')")
    @Log(title = "楼栋的 楼层数据", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<EstateBuildFloor> export(@Validated EstateBuildFloor estateBuildFloor) {
        List<EstateBuildFloor> list = estateBuildFloorService.list();
        ExcelUtil<EstateBuildFloor> util = new ExcelUtil<EstateBuildFloor>(EstateBuildFloor.class);
        return util.exportExcel(list, "楼栋的 楼层数据");
    }

    /**
     * 获取楼栋的 楼层数据详细信息
     */
    @ApiOperation("获取楼栋的 楼层数据详细信息")
    @PreAuthorize("@ss.hasPermi('module:estateFloor:query')")
    @GetMapping("/{id}")
    public AjaxResult<EstateBuildFloor> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        EstateBuildFloor floor = estateBuildFloorService.getById(id);
		if(floor!= null){
			if(StrUtil.isNotEmpty(floor.getQrCode())){
				floor.setQrCode(imgUrl + floor.getQrCode());
			}
		}
        return AjaxResult.success(floor);
    }

    /**
     * 新增楼栋的 楼层数据
     */
    @ApiOperation("新增楼栋的 楼层数据")
    @PreAuthorize("@ss.hasPermi('module:estateFloor:add')")
    @Log(title = "楼栋的 楼层数据", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody EstateBuildFloor estateBuildFloor) {
		if (estateBuildFloor.getPropertyId()==null){
			if (estateBuildFloor.getEstateId()!=null){
				Estate estate = estateService.findById(estateBuildFloor.getEstateId());
				if (estate!=null){
					estateBuildFloor.setPropertyId(estate.getPropertyId());
				}
			}
		}
		boolean bl = estateBuildFloorService.save(estateBuildFloor);
		try{
			String fileName = "terminal_qr_" + estateBuildFloor.getId() + ".jpg";
			String content = "https://www.caihengyun.com/wxmini/floor/info?id=" + estateBuildFloor.getId();
			int upload_type = FileUploadUtils.TYPE_TERMINALS;
			System.out.println("content:  "+ content);
			String img_key = FileUploadUtils.getUploadPrefix(upload_type) + fileName;
			QRCodeUtilEx.createQrCodeImg(content, estateBuildFloor.getFloorName(), null,
				uploadPath +"/"+img_key, true, fileName, upload_type);
			estateBuildFloor.setQrCode(img_key);
			estateBuildFloorService.updateById(estateBuildFloor);
		}catch (Exception ex){
			ex.printStackTrace();
		}
        return toAjax(bl ? 1 : 0);
    }

	/**
	 * 重置二维码
	 */
	@Log(title = "重置二维码")
	@PostMapping("/resetQrCode")
	@ResponseBody
	@PreAuthorize("@ss.hasPermi('module:estateFloor:edit')")
	public AjaxResult<Void> resetQrCode(@RequestBody EstateBuildFloor estateBuildFloor) {
		if(estateBuildFloor.getId()!=null){
			try{
				estateBuildFloor = estateBuildFloorService.getById(estateBuildFloor.getId());
				String fileName = "terminal_qr_" + estateBuildFloor.getId() + ".jpg";
				String content = "https://www.caihengyun.com/wxmini/floor/info?id=" + estateBuildFloor.getId();
				int upload_type = FileUploadUtils.TYPE_TERMINALS;
				System.out.println("content:  "+ content);
				String img_key = FileUploadUtils.getUploadPrefix(upload_type) + fileName;
				QRCodeUtilEx.createQrCodeImg(content, estateBuildFloor.getFloorName(), null, uploadPath +"/"+img_key, true, fileName, upload_type);
				estateBuildFloor.setQrCode(img_key);
			}catch (Exception ex){
				ex.printStackTrace();
			}
			if (estateBuildFloorService.updateById(estateBuildFloor)) {
				return AjaxResult.success();
			}
		}
		return AjaxResult.error();
	}

    /**
     * 修改楼栋的 楼层数据
     */
    @ApiOperation("修改楼栋的 楼层数据")
    @PreAuthorize("@ss.hasPermi('module:estateFloor:edit')")
    @Log(title = "楼栋的 楼层数据", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody EstateBuildFloor estateBuildFloor) {
		if (estateBuildFloor.getPropertyId()==null){
			if (estateBuildFloor.getEstateId()!=null){
				Estate estate = estateService.findById(estateBuildFloor.getEstateId());
				if (estate!=null){
					estateBuildFloor.setPropertyId(estate.getPropertyId());
				}
			}
		}
        return toAjax(estateBuildFloorService.updateById(estateBuildFloor) ? 1 : 0);
    }

    /**
     * 删除楼栋的 楼层数据
     */
    @ApiOperation("删除楼栋的 楼层数据")
    @PreAuthorize("@ss.hasPermi('module:estateFloor:remove')")
    @Log(title = "楼栋的 楼层数据" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return toAjax(estateBuildFloorService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
